layui.use(['flow', 'form', 'layer', 'upload',"layedit"], function () {
    var flow = layui.flow,
        form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        upload = layui.upload,
        layedit=layui.layedit,
        $ = layui.jquery;

    //流加载图片
    var imgNums = 12; //单页显示图片数量

    flow.load({
        elem: '#Images', //流加载容器
        done: function (page, next) { //加载下一页
            admin = localStorage.getItem("admin"); 
            $.get("http://127.0.0.1:8000/bookList", { userId:admin }, function (res) {
                var imgList = [],
                    data = res.data;
            if(data!=null){
                 var maxPage = imgNums * page < data.length ? imgNums * page : data.length;
                setTimeout(function () {
                    //class="bookName"
                    for (var i = imgNums * (page - 1); i < maxPage; i++) {
                        imgList.push('<li><div class="uploadImgDiv"><input hidden value="' + data[i].pid + '"><img layer-src="' + data[i].bookImg + '" src="' +
                            data[i].bookImg + '" alt="' + data[i].bookabstract +
                            '"></div><div class="operate"><div class="check"><input  type="checkbox" value="' + data[i].pid + '"  name="belle" lay-filter="choose" lay-skin="primary" title="' +
                            data[i].bookName + '"><a hidden value="'+ data[i].Connect+'"></a><p hidden value="'+ data[i].classify+'"></p></div><i class="layui-icon img_del">&#xe640;</i></div></li>');
                    }

                    next(imgList.join(''), page < (data.length / imgNums));
                    form.render();
                }, 500);
            }else{
               
                next(imgList.join(''), page=0);
                form.render();
            }
                
             
               

            });
        }
    });

    //上传新图书
    function bookAdd(edit) {
        var index = layui.layer.open({
            title: "上传新图书",
            type: 2,
            area: ['90%', '50%'],
            fixed: false, //不固定
            maxmin: true,
            content: "bookAdd.html",
            success: function (layero, index) {
                var body = layui.layer.getChildFrame('body', index);
                if (edit) {
                    console.log(edit)
                    body.find(".mypid").val(edit.pid);
                    body.find(".bookName").val(edit.alt);
                    body.find(".bookabstract").val(edit.bookabstract);
                    body.find(".bookConnect").val(edit.Connect);
                    body.find(".technologyTpyeStatus option:selected").val(edit.classify);
                    body.find(".thumbImg").attr("src", edit.imgSrc);
                    form.render();
                }
                setTimeout(function () {
                    layui.layer.tips('点击此处返回文章列表', '.layui-layer-setwin .layui-layer-close', {
                        tips: 3
                    });
                }, 500)
            }
        })
    }
    

    $(".uploadNewBook").click(function () {
        bookAdd();
    })

    //弹出层
    $("body").on("click", ".uploadImgDiv img", function () {
        
        let imgSrc = $(this).attr('src');
        let bookabstract = $(this).attr('alt');
        let pid = $(this).parent().find("input").attr('value');
        let bookName = $(this).parent().parent().find(".operate .check input").attr('title');
        let Connect = $(this).parent().parent().find(".operate .check a").attr('value');
        let classify = $(this).parent().parent().find(".operate .check p").attr('value');
        var edit = {
            imgSrc, bookName, bookabstract,pid,Connect,classify
        }
        //console.log(edit)
        var index = layui.layer.open({
            title: "修改图书信息",
            type: 2,
            area: ['90%', '50%'],
            fixed: false, //不固定
            maxmin: true,
            content: "bookEdit.html",
            success: function (layero, index) {
                var body = layui.layer.getChildFrame('body', index);
                   body.find(".mypid").val(edit.pid);
                   body.find(".technologyTpyeStatus option:selected").text(edit.classify);//怎么渲染
                    body.find(".bookName").val(edit.bookName);
                    body.find(".bookabstract").val(edit.bookabstract);
                    body.find(".thumbImg").attr("src", edit.imgSrc);
                    body.find(".bookConnect").val(edit.Connect);
                    form.render();
                    var editIndex = layedit.build(body.find("#news_content"), {
                        height: 30,
                        tool: [
                            'link'
                        ]
                    });
                    // //用于同步编辑器内容到textarea
                    layedit.sync(editIndex);
                setTimeout(function () {
                    layui.layer.tips('点击此处返回文章列表', '.layui-layer-setwin .layui-layer-close', {
                        tips: 3
                    });
                }, 500)
            }
        })
        //页面层
        // layer.open({
        //     type: 1,
        //     title: '',
        //     area: ['90%', '80%'], //宽高
        //     shadeClose: true, //开启遮罩关闭
        //     end: function (index, layero) {
        //         return false;
        //     },
        //     content: '<div style="height:100%;display: flex;display: -webkit-flex;flex-direction: column;justify-content: center;align-items: center;"><img style="max-width:95%;height:auto;t" src="' + imgSrc + '" /></div>'
        // });

    })
    	//删除单张图片
	$("body").on("click", ".img_del", function() {
		var _this = $(this);
        let pid = $(this).parent().parent().find("input").attr('value');
        
		layer.confirm('确定删除报名信息吗？', {
			icon: 3,
			title: '提示信息'
		}, function(index) {
            //调用api成功或失败后关闭数据
            admin = localStorage.getItem("admin"); 
            $.get("http://127.0.0.1:8000/bookdel", {
                pid: pid,  //将需要删除的pid作为参数传入
                userId:admin,//用户ID
            }, function (data) {
                console.log(index)
            _this.parents("li").hide(1000);
			setTimeout(function() {
				_this.parents("li").remove();
			}, 950);
			layer.close(index);
            })
			
		});
	})

	//全选
	form.on('checkbox(selectAll)', function(data) {
		var child = $("#Images li input[type='checkbox']");
		child.each(function(index, item) {
			item.checked = data.elem.checked;
		});
		form.render('checkbox');
	});

	//通过判断是否全部选中来确定全选按钮是否选中
	form.on("checkbox(choose)", function(data) {
		var child = $(data.elem).parents('#Images').find('li input[type="checkbox"]');
		var childChecked = $(data.elem).parents('#Images').find('li input[type="checkbox"]:checked');
		if (childChecked.length == child.length) {
			$(data.elem).parents('#Images').siblings("blockquote").find('input#selectAll').get(0).checked = true;
		} else {
			$(data.elem).parents('#Images').siblings("blockquote").find('input#selectAll').get(0).checked = false;
		}
		form.render('checkbox');
	})

	//批量删除
	$(".batchDel").click(function() {
        // let all = $(this).parent().parent().parent().find("ul li .operate .check input:checked");
        // var alldel={
        //     all
        // }
        // console.log(alldel.all)
		var $checkbox = $('#Images li input[type="checkbox"]');
		var $checked = $('#Images li input[type="checkbox"]:checked');
       
		if ($checkbox.is(":checked")) {
           
                //console.log(checkID)
			layer.confirm('确定删除选中的图片？', {
				icon: 3,
				title: '提示信息'
			}, function(index) {
                //console.log($checked)
				var index = layer.msg('删除中，请稍候', {
					icon: 16,
					time: false,
					shade: 0.8
				});
                
                 var checkID=[];
                $("#Images li input[type='checkbox']:checked").each(function(i){
                      checkID[i] = $(this).attr('value');
                });
                admin = localStorage.getItem("admin"); 
                $.ajax({
                    url: "http://127.0.0.1:8000/bookalldel",
                    data: { allId: checkID ,userId:admin},//将需要删除的releaseId作为参数传入
                    type: "post",
                    dataType: "JSON",
                    success: function (res) {
                        
                        console.log(res.msg)
                        setTimeout(function() {
                    //调用api成功后关闭提示
					//删除数据
					$checked.each(function() {
                        
						$(this).parents("li").hide(1000);
						setTimeout(function() {
							$(this).parents("li").remove();
						}, 950);
					})
					$('#Images li input[type="checkbox"],#selectAll').prop("checked", false);
					form.render();
					layer.close(index);
                    window.location.reload();
					layer.msg("删除成功");
				}, 2000);
                    },
                    error: function (res) {

                    }
                })
				
			})
		} else {
			layer.msg("请选择需要删除的技术推荐");
		}
	})

})